package com.moly.websocketone.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.moly.websocketone.bean.Pet;
import com.moly.websocketone.util.AESUtil;
import org.springframework.core.MethodParameter;
import org.springframework.ui.ModelMap;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletResponse;


/**
 * @Description:  返回结果 加密处理
 * @Author: m01
 * @Date: created at  2018/11/15  16:31
 * @Modified By:
 */
public class AESInterceptor implements HandlerMethodReturnValueHandler {

    @Override
    public boolean supportsReturnType(MethodParameter methodParameter) {
        System.out.println(methodParameter);
        System.out.println("-- AESInterceptor supportsReturnType --");
        return methodParameter.getParameterType() == Pet.class;
    }

    @Override
    public void handleReturnValue(Object o, MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest) throws Exception {
        System.out.println("-- AESInterceptor handleReturnValue --");
        modelAndViewContainer.setRequestHandled(true);
        HttpServletResponse response = nativeWebRequest.getNativeResponse(HttpServletResponse.class);
        response.setContentType("text/plain;charset=UTF-8");


        ObjectMapper mapper = new ObjectMapper();
        String json=mapper.writeValueAsString(o);
        String enc=AESUtil.encryptAES(json, "djadiKJdj49dFJLd");

        response.getWriter().append(enc).flush();

    }


    //HandlerMethodReturnValueHandler
}
